<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon" id="niceScroll">
      <el-form
        :model="formData"
        label-width="164px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-form-item
          v-if="this.fromType != 'detail'"
          label="项目名称："
          prop="projectId"
        >
          <el-select
            class="mWidth"
            v-model="formData.projectId"
            placeholder="请选择"
            @change="ChangeSearch"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) of projectOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="项目名称：">
          {{ formData.projectName || '--' }}
        </el-form-item>
        <el-form-item label="保证金类型：" prop="type">
          <el-select
            class="sWidth"
            v-model="formData.type"
            filterable
            placeholder="请选择"
            @change="ChangeSearch"
            clearable
          >
            <el-option
              v-for="item in cashDepositOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="银行保函金额：" prop="bankTotal">
          <el-input
            style="position: relative"
            class="sWidth"
            v-model.trim="formData.bankTotal"
            placeholder="请输入银行保函金额"
          ></el-input>
          <span class="moneyUnit">元</span>
        </el-form-item>
        <el-form-item label="商业保险金额：" prop="insuranceTotal">
          <el-input
            style="position: relative"
            class="sWidth"
            v-model.trim="formData.insuranceTotal"
            placeholder="请输入商业保险金额"
          ></el-input>
          <span class="moneyUnit">元</span>
        </el-form-item>
        <el-form-item label="第三方担保金额：" prop="tripartiteTotal">
          <el-input
            style="position: relative"
            class="sWidth"
            v-model.trim="formData.tripartiteTotal"
            placeholder="请输入第三方担保金额"
          ></el-input>
          <span class="moneyUnit">元</span>
        </el-form-item>
        <el-form-item label="现金形式金额：" prop="cashTotal">
          <el-input
            style="position: relative"
            class="sWidth"
            v-model.trim="formData.cashTotal"
            placeholder="请输入现金形式金额"
          ></el-input>
          <span class="moneyUnit">元</span>
        </el-form-item>
        <el-form-item label="应退日期：" prop="shouldReturnDate">
          <el-date-picker
            type="date"
            placeholder="请选择应退日期"
            class="sWidth"
            v-model="formData.shouldReturnDate"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="缴纳凭证：" prop="fileHand">
          <uploadAnnex
            @getFileList="getFileListPay"
            :limitationFactor="limitationFactor"
            @getFile="getFilePay"
            :upLoadFile="formData.fileHand"
          />
        </el-form-item>
        <el-row v-model="formData.fileHand">
          <uploadResult
            style="margin-left: 120px"
            :resultList="formData.fileHand"
            @callBackResult="getFilePay"
          />
        </el-row>
        <el-form-item class="operateBtns">
          <el-button
            class="commonBut saveBtn"
            type="primary"
            @click="toSave"
            :loading="isSaveLoading"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
export default {
  name: 'threeTermsCashDepositAdd',
  data() {
    return {
      show: false,
      titleText: '添加保证金',
      back: true,
      projectOptions: [], //项目名称下拉框
      cashDepositOptions: [], //保证金类型
      formData: {
        projectId: '',
        type: '',
        bankTotal: '',
        insuranceTotal: '',
        tripartiteTotal: '',
        cashTotal: '',
        shouldReturnDate: '',
        fileHand: [],
      },
      upLoadFile: [], //附件
      srcList: [],
      oldSrcList: [],
      paySrcList: [],
      oldPaySrcList: [],
      //验证
      formRules: {
        projectId: [
          {
            required: true,
            message: '请选择项目名称',
            trigger: ['blur', 'change'],
          },
        ],
        type: [
          {
            required: true,
            message: '请选择保证金类型',
            trigger: 'change',
          },
        ],
        bankTotal: [
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入正整数',
            trigger: 'blur',
          },
        ],
        insuranceTotal: [
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入正整数',
            trigger: 'blur',
          },
        ],
        tripartiteTotal: [
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入正整数',
            trigger: 'blur',
          },
        ],
        cashTotal: [
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入正整数',
            trigger: 'blur',
          },
        ],
        shouldReturnDate: [
          {
            required: true,
            message: '应退日期不能为空',
            trigger: 'change',
          },
        ],
      },
      isSaveLoading: false, // 保存loading
      total: 0,
      pageSizeNumber: 20,
      pageNo: 1,
      projectSelect: '',
      item: '',
      amountPayableList: [],
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        methodTip:
          '请上传缴纳回执单，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      type: '', //是否从详情页面进入
      id: '',
    }
  },
  async created() {
    this.id = this.$route.query.id || ''
    this.fromType = this.$route.query.fromType || ''
    this.titleText = this.fromType == 'detail' ? '修改保证金' : '添加保证金'
    //项目名称下拉框
    await this.getProjectList()
    await this.getTypeOption()
    //初始化数据
    if (this.fromType === 'detail') {
      await this.getInfo()
    }
  },
  mounted() {},
  methods: {
    getTypeOption() {
      return this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/type',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.cashDepositOptions = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getProjectList() {
      return this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/current/projects',
      })
        .then((response) => {
          this.projectOptions = response.data.result
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    ChangeSearch() {
      // if(!this.fromType){
      //   if (this.formData.projectId && this.formData.type) {
      //     this.verifyIsExesit(this.formData.projectId, this.formData.type);
      //   }
      // }
    },
    verifyIsExesit(projectId, type) {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/exist',
        data: {
          projectId: projectId,
          type: type,
        },
      })
        .then((response) => {
          if (!response.data.result === true) {
            this.toSubmit()
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '保证金已存在',
              type: 'error',
            })
            return
          }
        })
        .catch((error) => {})
    },
    getInfo() {
      this.isSaveLoading = true
      return this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/detail',
        data: {
          id: this.id,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          var data = response.data.result
          this.formData.projectName = data.projectName
          this.formData.projectId = data.projectId
          this.formData.type = data.type
          this.formData.bankTotal = data.bankTotal
          this.formData.insuranceTotal = data.insuranceTotal
          this.formData.tripartiteTotal = data.tripartiteTotal
          this.formData.employeeNation = data.nationality
          this.formData.cashTotal = data.cashTotal
          this.formData.shouldReturnDate = data.shouldReturnDate
          this.formData.fileHand = data.fileHandList
          for (var i = 0; i < this.formData.fileHand.length; i++) {
            this.srcList.push(this.formData.fileHand[i].url)
            this.oldSrcList.push(this.formData.fileHand[i].url)
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    //保存跳转到列表
    toSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (!this.fromType) {
            if (this.formData.projectId && this.formData.type) {
              this.verifyIsExesit(this.formData.projectId, this.formData.type)
            }
          } else {
            this.toSubmit()
          }
        } else {
          return false
        }
      })
    },
    toSubmit() {
      if (
        !this.formData.bankTotal &&
        !this.formData.insuranceTotal &&
        !this.formData.tripartiteTotal &&
        !this.formData.cashTotal
      ) {
        this.$message.error('金额至少填报一项')
      } else {
        this.isSaveLoading = true
        this.submitFormUptate()
      }
    },
    submitFormUptate(params) {
      let data = {
        projectId: this.formData.projectId,
        type: this.formData.type,
        bankTotal: this.formData.bankTotal,
        insuranceTotal: this.formData.insuranceTotal,
        tripartiteTotal: this.formData.tripartiteTotal,
        cashTotal: this.formData.cashTotal,
        shouldReturnDate: this.formData.shouldReturnDate,
        fileHand: JSON.stringify(this.formData.fileHand),
      }
      let url = 'api-d/trinomial/expand/save'
      //修改保存
      if (this.fromType === 'detail') {
        data.id = this.id
      }
      this.axios({
        method: 'post',
        url,
        data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$router.push({
              path: '/home/cashDeposit/threeTermsCashDeposit',
            })
            this.$store.commit('CHANGE_SLIDER_NAME', {
              oldUrl: '/home/cashDeposit/threeTermsCashDeposit',
              newUrl: this.$router.currentRoute.fullPath,
            })
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    //取消及返回列表
    goBack() {
      this.$router.push('/home/cashDeposit/threeTermsCashDeposit')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/cashDeposit/threeTermsCashDeposit',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFile(val) {
      this.upLoadFile = val
    },
    getFileListPay(val) {
      this.paySrcList.push(val)
      this.oldPaySrcList.push(val)
    },
    getFilePay(val) {
      this.formData.fileHand = val
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  // top: 198px;
  padding: 40px 10px;
  background: #fff;
  /deep/ .el-form-item__label {
    color: #333;
  }
  // /deep/ .el-form {
  //   .el-input__inner {
  //     width: 340px;
  //   }
  // }
  // .el-date-editor.el-input,
  // .el-date-editor.el-input__inner {
  //   width: 340px;
  // }
  .shouldTotal {
    color: #009588;
    font-weight: bold;
  }
  /deep/ textarea.el-textarea__inner {
    // width: 514px;
    height: 82px;
  }
  .operateBtns {
    margin-top: 20px;
  }
  .moneyUnit {
    position: absolute;
    left: 270px;
    top: 0;
  }
}
</style>
